use sqlx::MySqlPool;
use crate::model::environment::*;
use chrono::{TimeZone, FixedOffset};

pub struct EnvironmentRepository {
    pool: MySqlPool,
}

impl EnvironmentRepository {
    pub fn new(pool: MySqlPool) -> Self {
        Self { pool }
    }

    pub async fn find_all(&self) -> Result<Vec<EnvironmentData>, sqlx::Error> {
        let rows = sqlx::query!(
            "SELECT id, temperature, humidity, timestamp FROM environment_data"
        )
        .fetch_all(&self.pool)
        .await?;

        let china_timezone = FixedOffset::east_opt(8 * 3600).unwrap();
        
        Ok(rows
            .into_iter()
            .map(|row| {
                let naive_dt = row.timestamp.unwrap();
                let china_time = china_timezone.from_utc_datetime(&naive_dt);
                
                EnvironmentData {
                    id: row.id,
                    temperature: row.temperature,
                    humidity: row.humidity,
                    timestamp: Some(china_time),
                }
            })
            .collect())
    }

    pub async fn create(&self, data: &CreateEnvironmentData) -> Result<i64, sqlx::Error> {
        let result = sqlx::query!(
            r#"
            INSERT INTO environment_data (temperature, humidity)
            VALUES (?, ?)
            "#,
            data.temperature,
            data.humidity,
        )
        .execute(&self.pool)
        .await?;

        Ok(result.last_insert_id().try_into().unwrap())
    }
}